package pl.com.qapps.datastore.berkeley;

import java.util.LinkedList;
import java.util.List;

import pl.com.qapps.datastore.berkeley.impl.EntityBindings;

import com.google.appengine.api.datastore.Key;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;

public class DeleteRequest extends BaseRequest<Void> {

	private final List<DatabaseEntry> keysData = new LinkedList<>();
	private Iterable<Key> keys;

	void setKeys(Iterable<Key> keys) {
		keysData.clear();
		this.keys = keys;
	}

	@Override
	Void run(Store store, Transaction txn) {
		Database db = store.getEntityDb();
		for (DatabaseEntry keyData : keysData) {
			OperationStatus result = db.delete(txn, keyData);
			if (result != OperationStatus.SUCCESS
					|| result != OperationStatus.NOTFOUND) {
			}
		}
		return null;
	}

	@Override
	void init(Store store) {
		keysData.clear();
		for (Key key : keys) {
			DatabaseEntry keyData = new DatabaseEntry();
			EntityBindings.ENTITY_KEY_BINDING.objectToEntry(key, keyData);
			keysData.add(keyData);
		}
	}

}
